package com.itheima.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.UUID;

public class FileUtils {

    // Endpoint以杭州为例，其它Region请按实际情况填写。
    private static final String ENDPOINT = "https://oss-cn-beijing.aliyuncs.com";

    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
    private static final String ACCESS_KEY_ID = "LTAI4G69oiEaBzQha5seQQDR";

    private static final String ACCESS_KEY_SECRET = "sBrN8JjCYOnCTH9tEZ4tE48xepkvFa";
    //仓库名字
    private static final String BUCKET_NAME = "health115";


    public static String upload(String filename, InputStream inputStream) throws FileNotFoundException {

        //自定义随机名字，并按照原来类型存储(截取类型
        String objectName = UUID.randomUUID().toString() + filename.substring(filename.lastIndexOf("."));

        // <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
        String savePath = "heima/health115/";

        //拼接存放位置
        String realpath = savePath + objectName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

//        ossClient.putObject(BUCKET_NAME,realpath,new FileInputStream("C:\\Users\\71507\\Desktop\\图片\\幻灵镇魂曲\\3.png"));
        ossClient.putObject(BUCKET_NAME, realpath, inputStream);

        try {
//            System.out.println("");
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 关闭OSSClient。3.关闭oss连接
        ossClient.shutdown();
        return realpath;
    }

    public static void deletefile(String realpath){
        // 创建OSSClient实例。 1.连接oss
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        // 上传文件到指定的存储空间（bucketName）并将其保存为指定的文件名称（objectName）。2.操作
        ossClient.deleteObject(BUCKET_NAME,realpath);
        // 关闭OSSClient。3.关闭oss连接
        ossClient.shutdown();
    }

//    public static void main(String[] args) throws FileNotFoundException {
////        String upload = upload("2.png", null);
////        System.out.println(upload);
//        deletefile("heima/health115/c15f7bc4-b56a-4c14-96c6-ee4e0aef1fcb.png");
//    }
}
//https://health115.oss-cn-beijing.aliyuncs.com/heima/health115/70f687d7-9912-4dd6-b26d-2ea0d425fa8a.jpg